<script setup>
import util from '@/utils/util'
import {User} from '@/utils/resource'
import {showSaveResponse, validFieldExists, validateForm} from '@/utils/element-helper'
import {reactive, ref} from "vue";
import {departmentStore} from "@/store/department";
import {appStore} from "@/store/user";
import {useRouter} from "vue-router";

const departmentS = departmentStore()
const appS = appStore()
const router = useRouter()
const props = defineProps({
  id: {
    type: String,
    default: "new"
  }
})
const isNew = props.id === 'new'
const isNormal = ref(false)//非普通用户才能选择角色
const loading = ref(false)

const state = reactive({
  form: {
    roleId: "0",
    gender: "1",
    status: "1",
    departmentIds: [],
    birthday: null,
  },
  initForm: {}
})

if (!isNew) {
  loadUser()
}

async function loadUser() {
  let res = await User.get(props.id)
  res.data.roleId = String(res.data.roleId)
  res.data.gender = String(res.data.gender)
  res.data.status = String(res.data.status)
  res.data.departmentIds = util.getTreePath(departmentS.departments, res.data.departmentId)
  res.data.pass = ''
  isNormal.value = appS.user.roleId !== -1;
  state.form = res.data
  state.initForm = util.copy(res.data)
}

const rules = reactive({
  name: [
    {required: true, message: '账号不能为空', trigger: 'blur'},
    {validator, trigger: 'blur'}
  ],
  email: [
    {required: true, message: '邮箱地址不能为空', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur']},
    {validator, trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '手机号码不能为空', trigger: 'blur'},
    {pattern: /^1[34578]\d{9}$/, message: '目前只支持中国大陆的手机号码'},
    {validator, trigger: 'blur'}
  ],
  pass: [
    {min: 5, max: 25, message: '密码长度在 5 到 25 位之间', trigger: 'blur'},
    {validator: validatePass, trigger: 'blur'}
  ],
  departmentId: [
    {required: true, message: '部门不能为空', trigger: 'change', type:'number'},
  ],
})

function validator(rule, value, callback) {
  validFieldExists(rule, value, callback, state.initForm[rule.field] !== value || isNew, (rule, value) => User.exists(rule, value))
}

function validatePass(rule, value, callback) {
  if (isNew && (value === '' || value === undefined)) {
    callback(new Error("密码不能为空"))
  } else {
    callback()
  }
}

const form = ref(null)

function submitForm(formName) {
  state.form.departmentId = state.form.departmentIds[state.form.departmentIds.length - 1]
  return validateForm(form.value, formName, () => {
    let tempFrom = util.copy(state.form)
    //不修改密码需要将密码清空
    if (tempFrom.pass === '') {
      delete tempFrom['pass']
    }
    showSaveResponse(loading.value,() => User.save(tempFrom, isNew ? 'post' : 'put'), () => router.back())
  })
}

</script>

<template>
  <div>
    <div style="padding-left: 20px">
      <p style="font-size: 20px">用户</p>
      <el-form :model="state.form" label-position="left" :rules="rules" ref="form" label-width="140px"
               class="user-form" :loading="loading">
        <el-form-item label="账号" prop="name" class="my-form-item">
          <el-input v-model="state.form.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass" class="my-form-item">
          <el-input v-model="state.form.pass" type="password" placeholder="密码（无需修改请留空）"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" class="my-form-item">
          <el-input v-model="state.form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone" class="my-form-item">
          <el-input v-model="state.form.phone"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nick" class="my-form-item">
          <el-input v-model="state.form.nick"></el-input>
        </el-form-item>
        <!--<el-form-item label="头像" prop="nick">-->
        <!--<el-input v-model="form.avatar"></el-input>-->
        <!--</el-form-item>-->
        <el-form-item label="生日" prop="birthday" class="my-form-item">
          <el-date-picker type="date" placeholder="选择生日" v-model="state.form.birthday"
                          style="width: 100%"  format="YYYY-MM-DD"
                          value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
        </el-form-item>
        <el-form-item label="用户类型" prop="roleId" class="my-form-item">
          <el-radio-group v-model="state.form.roleId">
            <el-radio label="0">一般用户</el-radio>
            <el-radio :disabled="isNormal" label="-1">超级管理员</el-radio>
          </el-radio-group>
          <span v-if="isNormal" style="color:#F56C6C">&nbsp;&nbsp;&nbsp;一般用户不能选择超级管理员角色</span>
        </el-form-item>
        <el-form-item label="部门" prop="departmentId" class="my-form-item">
          <el-cascader :options="departmentS.departments"
                       change-on-select clearable
                       :props="{
                          value: 'id',
                          label: 'name',
                          children: 'children'
                       }" v-model="state.form.departmentIds"></el-cascader>
        </el-form-item>
        <el-form-item label="性别" prop="gender" class="my-form-item">
          <el-radio-group v-model="state.form.gender">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status" class="my-form-item">
          <el-select v-model="state.form.status" placeholder="请选择">
            <el-option label="正常" value="1"></el-option>
            <el-option label="失效" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最近访问时间" prop="visited" class="my-form-item">
          <el-input v-model="state.form.visited" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="created" class="my-form-item">
          <el-input v-model="state.form.created" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="更新时间" prop="updated" class="my-form-item">
          <el-input v-model="state.form.updated" disabled="disabled"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div style="padding: 15px">
      <router-link to="/user">
        <el-button plain round type="info" icon="Back" style="margin-right: 10px;">返回</el-button>
      </router-link>
      <el-button plain type="primary" @click="submitForm('form')" icon="CircleCheck">保存</el-button>
    </div>
  </div>
</template>


<style scoped>
.user-form {
  width: 90%;
}

.my-form-item {
  max-width: 600px;
}

</style>
